import time
from selenium import webdriver
import requests
import json
import base64
import urllib
import random

import redis

host = '127.0.0.1'
port = 6379
r = redis.Redis(host=host, port=port)

for i in range(3):
    source = 'abcdefghijklmn'
    sou_str = ''
    for j in range(5):
        tmp_num = random.randrange(len(source))

        random_str = source[tmp_num]
        sou_str += random_str

    browser = webdriver.Chrome('C:/Users/xiaolu/Downloads/chromedriver_win32/chromedriver.exe')
    browser.get('http://localhost:8080/register')
    # 截取图片验证码并保存
    myimg = browser.find_element_by_id('mycode').screenshot('register.png')

    # 截取屏幕
    # browser.get_screenshot_as_file('register.png')
    time.sleep(3)

    # 请求百度接口
    res = requests.get(
        'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=bIVdIuFvUcBnaz2FCxzwdKHY&client_secret=Ij19VrsofEltu2kA30EEPbtdlTynBffC')

    # 转码
    res = json.loads(str(res.text))
    token = res['access_token']

    # 识别图像
    url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token

    # 构造头部
    header = {'Content-Type': 'application/x-www-form-urlencoded'}

    # 构造图片
    img = open('./register.png', 'rb')
    temp_img = img.read()
    img.close()

    # 构建参数
    data = {'image': base64.b64encode(temp_img)}
    # 编码
    data = urllib.parse.urlencode(data)

    # 发送请求
    res = requests.post(url=url, data=data, headers=header)

    # 将json数据转为python格式数据
    codd = json.loads(res.text)
    code = codd['words_result'][0]['words']

    # 模拟注册
    browser.find_element_by_xpath('/html/body/div/div/form/div[1]/div/div/input').send_keys(sou_str)
    # 将注册后的用户名存到redis库中
    r.set('sou_str', sou_str)
    browser.find_element_by_xpath('/html/body/div/div/form/div[2]/div/div/input').send_keys('123456')
    browser.find_element_by_xpath('/html/body/div/div/form/div[3]/div/div/input').send_keys(code)

    # 点击注册按钮
    browser.find_element_by_xpath('/html/body/div/div/form/button/span').click()

    browser.close()
